import { FC, useEffect, useState } from 'react'
import { Button, Form, Input, message, Modal, Space, Switch, Table } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'

import styles from './index.module.scss'
import request from '../../utils/request'
import { transListToTree } from '../../utils/utils'
const { confirm } = Modal

const Permission: FC = () => {
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: '25%'
    },
    {
      title: '标识',
      dataIndex: 'code',
      key: 'code',
      width: '25%'
    },
    {
      title: '描述',
      dataIndex: 'descrition',
      key: 'descrition',
      width: '25%'
    },
    {
      title: '操作',
      dataIndex: 'Action',
      render: (text: any, record: any) => (
        <Space size="middle">
          {record.type === 1 ? (
            <Button type="link" onClick={() => addPermissionHandler(2, record.id)}>
              添加
            </Button>
          ) : null}
          <Button type="link" onClick={() => editPermissionHandler(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => delPermissionHandler(record)}>
            删除
          </Button>
        </Space>
      ),
      width: '25%'
    }
  ]

  const rules = {
    name: [{ required: true, message: '权限名称为必填项' }],
    code: [{ required: true, message: '权限标识为必填项' }]
  }

  const [form] = Form.useForm()

  // --------------------------------------  获取权限管理数据 ----------------------------------
  const [permissList, setPermissList] = useState()

  const getPermissionList = async () => {
    const res = await request.get('/api/sys/permission')
    const treeData = transListToTree(res.data.data, '0')
    console.log(treeData)
    setPermissList(treeData)
  }

  useEffect(() => {
    getPermissionList()
  }, [])

  const data = permissList

  // --------------------------------------  弹框有关 ----------------------------------
  const [addPermission, setAddPermission] = useState({
    title: '新建属性组',
    isShow: false,
    type: 'add'
  })

  interface IPermisson {
    id?: string
    name: string
    code: string
    description: string
    enVisible: string
  }

  const [editPerData, setEditPerData] = useState({})
  const handleOk = async () => {
    const values = (await form.validateFields()) as IPermisson

    if (addPermission.type === 'add') {
      const params = { ...values, ...addData, enVisible: Number(values.enVisible) }

      const res = await request.post('/api/sys/permission', params)
      console.log(res)

      message.info(res.data.message, 0.5, () => {
        // 获取到输入框的值
        setAddPermission({
          ...addPermission,
          isShow: false
        })
        getPermissionList()
      })
    } else if (addPermission.type === 'edit') {
      const params = { ...editPerData, ...values }
      const res = await request.put(`/api/sys/permission/${params.id}`, params)

      message.info(res.data.message, 0.5, () => {
        // 获取到输入框的值
        setAddPermission({
          ...addPermission,
          isShow: false
        })
        getPermissionList()
      })
    }
  }

  const handleCancel = () => {
    setAddPermission({
      ...addPermission,
      isShow: false
    })
  }

  // --------------------------------------  新增和编辑权限点 ----------------------------------
  const [addData, setAddData] = useState({})

  const addPermissionHandler = (type?: number, pid?: string) => {
    setAddData({ type, pid })
    setAddPermission({
      title: '新增权限点',
      isShow: true,
      type: 'add'
    })
  }

  const editPermissionHandler = async (record: any) => {
    const res = await request.get(`/api/sys/permission/${record.id}`)
    form.setFieldsValue(res.data.data)
    setEditPerData(res.data.data)

    setAddPermission({
      title: '编辑权限点',
      isShow: true,
      type: 'edit'
    })
  }

  // --------------------------------------  删除权限点 ----------------------------------
  const delPermissionHandler = (record: any) => {
    confirm({
      title: '删除权限',
      icon: <ExclamationCircleOutlined />,
      content: '你确定需要删除该权限吗 ？',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        await request.delete(`/api/sys/permission/${record.id}`)

        message.info('删除权限成功', 0.5, () => {
          getPermissionList()
        })
      },
      onCancel() {
        console.log('Cancel')
      }
    })
  }

  return (
    <div className={styles.root}>
      <Button
        style={{ float: 'right', marginBottom: '20px' }}
        type="primary"
        onClick={() => addPermissionHandler(1, '0')}
      >
        添加权限
      </Button>

      <Table rowKey="id" bordered columns={columns} dataSource={data} />

      <Modal
        destroyOnClose
        title={addPermission.title}
        visible={addPermission.isShow}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          preserve={false}
          autoComplete="off"
        >
          <Form.Item name="id" hidden>
            <Input type="hidden" />
          </Form.Item>

          <Form.Item label="权限名称" name="name" rules={rules.name}>
            <Input />
          </Form.Item>

          <Form.Item label="权限标识" name="code" rules={rules.code}>
            <Input />
          </Form.Item>

          <Form.Item label="权限描述" name="description">
            <Input />
          </Form.Item>

          <Form.Item label="开启" name="enVisible" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Permission
